﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Newtonsoft.Json;

namespace Happy.Web.Mvc.Newtonsoft
{
    /// <summary>
    /// Json 格式的模型绑定器。
    /// </summary>
    public sealed class NewtonsoftJsonBinder : IModelBinder
    {
        public static readonly NewtonsoftJsonBinder Instance = new NewtonsoftJsonBinder();

        /// <inheritdoc />
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string json = controllerContext.HttpContext.Request[bindingContext.ModelName];

            if (json == null)
            {
                return null;
            }

            var result = JsonConvert.DeserializeObject(json, bindingContext.ModelType, new GuidConverter(), new NullableGuidConverter());

            return DeserializePostProcesserRegistry
                .GetProcesser(bindingContext.ModelType)
                .OnDeserialized(result);
        }
    }
}